﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Threading.Tasks;
using Windows.Storage;
using Windows.Storage.BulkAccess;
using Windows.Storage.FileProperties;
using Windows.Storage.Search;

namespace MetroContractSample.Data
{
  public class MyDataLoader
  {
    private readonly object lockHandle = new object();

    public async Task GatherUserData(SampleDataSource sampleData)
    {
      lock (lockHandle)
      {
        sampleData.ItemGroups.Clear();
      }

      List<StorageFolder> folders = new List<StorageFolder>(){ 
                KnownFolders.DocumentsLibrary,
                KnownFolders.HomeGroup,
                KnownFolders.MediaServerDevices,
                KnownFolders.MusicLibrary,
                KnownFolders.PicturesLibrary, 
                KnownFolders.RemovableDevices,
                KnownFolders.VideosLibrary,
            };

      Dictionary<SampleDataGroup, QueryOptions> searchConditions
          = new Dictionary<SampleDataGroup, QueryOptions>();

      searchConditions.Add(
           new SampleDataGroup("documents", "文書", "txt docx pptx pdf", "自動的に読み込める文書ファイル"),
           new QueryOptions(CommonFileQuery.DefaultQuery, new[] { ".txt", ".docx", ".pdf", ".pptx", }) { FolderDepth = FolderDepth.Deep, }
      );
      searchConditions.Add(
           new SampleDataGroup("pictures", "画像", "jpg png bmp gif", "自動的に読み込める画像ファイル"),
           new QueryOptions(CommonFileQuery.DefaultQuery, new[] { ".jpg", ".png", ".bmp", ".gif", }) { FolderDepth = FolderDepth.Deep, }
      );

      IEnumerable<Task> tasks = searchConditions.Select(kv => GatherSpecifiedKindData(sampleData, kv.Key, kv.Value, folders));
      await Task.WhenAll(tasks);

    }


    private async Task GatherSpecifiedKindData(SampleDataSource sampleData, SampleDataGroup group, QueryOptions queryOptions, IList<StorageFolder> folders)
    {
      lock (lockHandle)
      {
        sampleData.ItemGroups.Add(group);
      }

      IEnumerable<Task> tasks = folders.Select(folder => FindFilesAndAdd(group, queryOptions, folder));
      await Task.WhenAll(tasks);
    }

    private async Task FindFilesAndAdd(SampleDataGroup group, QueryOptions queryOptions, StorageFolder folder)
    {
      StorageFileQueryResult query = folder.CreateFileQueryWithOptions(queryOptions);
      var fileInfoFactory = new FileInformationFactory(query, ThumbnailMode.SingleItem);

      IReadOnlyList<FileInformation> fileInfoList;
      try
      {
        fileInfoList = await fileInfoFactory.GetFilesAsync();
      }
      catch
      {
        return;
      }

      foreach (var file in fileInfoList)
      {
        SampleDataItem item = new SampleDataItem(file, group);
        lock (lockHandle)
        {
          group.Items.Add(item);
        }
      }
    }

  }
}
